import React, { useState } from 'react';
import { Button, Select, Form, Field, Table, Card, Dialog,Input,NumberPicker,DatePicker, Message } from '@alifd/next';
import { useFusionTable } from 'ahooks';
import moment, { months } from 'moment'
import EmptyBlock from './EmptyBlock';
import ExceptionBlock from './ExceptionBlock';

import styles from './index.module.scss';
import actions from '@/utils/action'


function getColumnKey(column: any & { key?: string }): string | null {
  if (column) {
    return column.key || String(column.title) || column.dataIndex;
  }
  return null;
}


const FormItem = Form.Item;

const FORM_ITEMS = [{
  label:'辅材名称',
  require:true,
  name:'itemName',
  Comp:Input
},
{
  label:'辅材编码',
  require:true,
  name:'itemCode',
  Comp:Input
},
{
  
    label:'单据号',
    require:true,
    name:'code',
    Comp:Input
  
},
{
  
  label:'辅材类型',
  require:true,
  name:'type',
  dataSource:['软跳纤','网线','轧带','电源线及电缆端子','汇聚分流器'],
  Comp:Select
},
{
  label:'单据类型',
  require:true,
  name:'orderType',
  dataSource:['入库单','出库单'],
  Comp:Select
},{
  label:'数量',
  name:"count",
  require:true,
  Comp:NumberPicker
},
{
  label:'说明',
  name:"desc",
  Comp:Input
},
{
  label:'时间',
  name:'createTime',
  Comp:Input,
  visible:false,
  // type:'datetime'
  cell:(va)=>{

    // return new Date(va).toDateString()
    return moment(new Date(va)).format('YYYY-MM-DD HH:mm:ss')
  }
},
]
const TYPE = 'ORDER';


let dialogInstance:any = null;
const getTableData = async ({ current, pageSize }: { current: number; pageSize: number },  { type,orderType,createTime }): Promise<any> => {
  const list = actions.get(TYPE).filter((item)=>{
    if(type && item.type != type) {
      return false
    }
    if(orderType && item.orderType !=type){
      return false

    }
    if(createTime){
      const [pre,next] = createTime;
      const n = moment(new Date(item.createTime).getTime());
      if(n.isBefore(pre) || n.isAfter(next)){
        return false
      }
    }

    return true;

  })  
  
  
  return {
    list
  }
};


// 根据 hidden 切换当前 column 是否显示
const filterColumns = (columnList:any) => {
  const newColumnList = [...columnList];
  return newColumnList
    .filter((columnItem) => {
      if (columnItem.hidden) {
        return false;
      }
      return true;
    })
    .map((columnItem) => {
      if (columnItem.children) {
        const groupProps = { ...columnItem };
        delete groupProps.children;

        return (
          <Table.ColumnGroup key={getColumnKey(columnItem)} {...groupProps}>
            {filterColumns(columnItem.children)}
          </Table.ColumnGroup>
        );
      }

      return <Table.Column key={getColumnKey(columnItem)} {...columnItem} />;
    });
};


const defaultColumnWidth = {
  'name.last': 140,
  email: 500,
  phone: 500,
  gender: 140,
};

const FilterTable: React.FunctionComponent = (): JSX.Element => {
  const [columnWidth, onColumnWidthChange] = useState(defaultColumnWidth);
  const field = Field.useField([]);
  const { paginationProps, tableProps, search, error, refresh } = useFusionTable(getTableData, {
    field,
  });
  const { submit, reset } = search;

  const onResizeChange = (dataIndex: keyof typeof defaultColumnWidth, width: number) => {
    const newWidth = {
      ...columnWidth,
    };
    newWidth[dataIndex] += width;
    onColumnWidthChange(newWidth);
  };
  const defaultColumns:any = (FORM_ITEMS.map(i=>{
    const {label:title,name:dataIndex,type='string',cell}:any = i;
    if(cell){
      return {
        title,dataIndex,type,cell
      }
    }else {
      return {
        title,dataIndex,type
      }
    }

  }) as any).concat({
    title:"操作",
    dataIndex:"ANY",
    type:"string",
    cell:($0,$1,record)=>{
  
      return <Button type="primary" text={true} onClick={()=>{
        actions.del(TYPE)(record);
        refresh();
      }}>删除</Button>
    }
  })

  return (
    <div className={styles.FilterTable}>
      <Card free>
        <Card.Content>
          <Form className="filter-form" responsive fullWidth labelAlign="top" field={field}>
            <FormItem colSpan={3} label="辅材类型">
              <Select
                name="type"
                dataSource={['软跳纤','网线','轧带','电源线及电缆端子','汇聚分流器']}
              />
            </FormItem>
            <FormItem colSpan={3} label="单据类型">
              <Select
                name="orderType"
                dataSource={['入库单','出库单']}
              />
            </FormItem>
            <FormItem colSpan={3} label="时间" >
              <DatePicker.RangePicker name="createTime"></DatePicker.RangePicker>
            </FormItem>
            <FormItem colSpan={7} />
            <FormItem
              colSpan={2}
              style={{
                display: 'flex',
                alignItems: 'center',
              }}
            >
              <Form.Submit type="primary" onClick={submit} validate style={{ marginRight: '20px' }}>
                提交
              </Form.Submit>
              <Form.Reset onClick={reset}>重置</Form.Reset>
            </FormItem>
          </Form>
        </Card.Content>
      </Card>
      <Card free>
        <Card.Content>
        <div className={styles.actionBar}>
          <div className={styles.buttonGroup}>
            <Button type="primary"
              style={{ marginBottom:10}}
            onClick={() => {
              const handleSubmit = async (data,err)=>{
                if(err) return;

                const {itemCode} = data;
                const fucai = actions.getFucai(itemCode)

                if(!fucai){
                  Message.error('操作失败，找不到相应辅材')
                  return;
                };

                const {count} = fucai;
                let newCount;
                if(data.orderType == '出库单'){
                  if(data.count > count){
                    Message.error('数量不足，出库失败');
                    return;
                  }
                  newCount = +count - +data.count;
                }else {
                  newCount = +count + +data.count
                }
                data.createTime = new Date().getTime();
                actions.add(TYPE)(data,{code:itemCode,newCount})
                refresh();
                dialogInstance.hide();
              }

              dialogInstance = Dialog.show({
                title:'添加',
                footer:false,
                style:{ width:500},
                content:<Form>
                  {
                    FORM_ITEMS.map(i=>{
                      const {Comp,require,label,visible=true,...rest}:any = i;
                      return visible ?<Form.Item required={require} label={label}>
                      <Comp {...rest}/>
                    </Form.Item>:null
                    })
                  }
                  <Form.Submit validate onClick={handleSubmit} type="primary">提交</Form.Submit>
    
                </Form>
              })
            }}>
              新增
            </Button>
          </div>
        </div>
          <Table
            {...tableProps}
            onResizeChange={onResizeChange}
            emptyContent={error ? <ExceptionBlock onRefresh={refresh} /> : <EmptyBlock />}
            primaryKey="email"
          >
          {filterColumns(defaultColumns)}
          </Table>
        </Card.Content>
      </Card>
    </div>
  );
};

export default FilterTable;
